package cn.madis.tran;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;

/**
 * @BelongsProject: rocketmq-test
 * @BelongsPackage:
 * @Author: zt
 * @CreateTime:
 * @Description: 消息生产者
 * @Version: 1.0
 */
public class Producer {

    public static void main(String[] args) throws Exception {
        // 1.创建生产者对象，指定生产者组名
        TransactionMQProducer producer = new TransactionMQProducer("tran_hello_group");
        // 2.连接mq
        producer.setNamesrvAddr("127.0.0.1:9876");
        //指定事务监听器
        producer.setTransactionListener(new MyTranListener());
        // 3.启动生产者
        producer.start();
        // 4.发送消息
        // 4.1.创建消息体
        // topic：消息主题 tags：此主题下的二级分类 body：消息的字节
        Message message = new Message("tran_topic", "hello_tags", "我在源码学习Java！".getBytes(StandardCharsets.UTF_8));
        // 4.2.发送消息
        TransactionSendResult transactionSendResult = producer.sendMessageInTransaction(message, null);
        // 4.3.打印消息发送结果
        System.out.println(transactionSendResult);
        // 5.关闭生产者
        producer.shutdown();
    }

}